﻿using Acme.BookStore.IIds4;

using IdentityModel.Client;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Acme.BookStore.Ids4
{
 /*
 * 文件名:Ids4Service
 * 功能：ids4服务管理
 * 创建时间：2021-11-15
 * 作者:gavin
 */
    /// <summary>
    /// ids4服务注册类
    /// </summary>

    public class Ids4Service : Volo.Abp.Application.Services.ApplicationService , IIds4Service
    {
        private IConfiguration _configuration;
        public Ids4Service(IConfiguration configuration)
        {
            this._configuration = configuration;
        }

        /// <summary>
        ///  生成Token
        /// </summary>
        /// <param name="LoginName"></param>
        /// <param name="Loginpwd"></param>
        /// <returns></returns>

        public async Task<string> GetIdsTokenAsync(string LoginName, string Loginpwd)
        {
            var client = new HttpClient();
            var idsTokenUrl = this._configuration.GetSection("AuthServer:Authority").Value;//ids4访问url地址
            var AppClientId = this._configuration.GetSection("AuthServer:AppClientId").Value;//ids4访问
            var AppClientSecret = this._configuration.GetSection("AuthServer:AppClientSecret").Value;//ids4访问密码
            var disco = client.GetDiscoveryDocumentAsync(idsTokenUrl);

            var tokenResponse = await client.RequestPasswordTokenAsync(
                new PasswordTokenRequest
                {
                    Address = disco.Result.TokenEndpoint,
                    ClientId = AppClientId,
                    ClientSecret = AppClientSecret,
                    UserName = LoginName,
                    Password = Loginpwd
                });

            if (tokenResponse.IsError)
            {
                return string.Empty;
            }
            return tokenResponse.AccessToken;
        }
    }
}
